#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2023/4/13 10:19
# @Author  : jiangwei
# @Site    : 
# @File    : jddj_api.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

import requests
import json
import logging
from urllib.parse import urlencode
from jddj.util import init_jddj_headers
from common.config import jddj_download_dir
from utils.trans_date import get_yesterday


logging.getLogger('urllib3.connectionpool').setLevel(logging.ERROR)


def format_jddj_params(type_hour=True):
    """
    参数控制  京东到家---结算管理---对账单查询---商家账单（京东到家）
            京东到家---结算管理---对账单查询---商家账单（小时购）
            时间段 按“已完成”
    :param type_hour:
    :return:
    """
    if type_hour:
        # params = {
        #     'orgCode': '325760',
        #     'orderIds': '',
        #     'pageNum': '1',
        #     'shopIds': '',
        #     'pageSize': '15',
        #     'loginName': 'jd_mcyp',
        #     'jdFusion': 'true',
        #     'billType': '2',  # 小时购为2，京东到家为1
        #     'settleStatus': '',
        #     'orderType': '',
        #     'srcOrderIds': '',
        #     'jdPayMark': '',
        #     'jdPayReqId': '',
        #     'orderChannelDesc': '',
        #     'orderStartTime': '20230411',
        #     'orderEndTime': '20230411',
        # }
        # 已完成
        params = {
            'orgCode': '325760',
            'orderIds': '',
            'orderId': '',
            'shopIds': '',
            'shopId': '',
            'loginName': 'jd_mcyp',
            'jdFusion': 'true',
            'billType': '2',
            'sourceId': 'pc',
            'srcOrderId': '',
            'userPin': 'jd_mcyp',
            'settleVender': '1',
            'groupNo': '',
            'settleStatus': '',
            'orderType': '',
            'srcOrderIds': '',
            'jdPayMark': '',
            'settleOrderId': '',
            'orderChannelDesc': '',
            'finishStartTime': '20240610',
            'finishEndTime': '20240610',
            'pageNum': '1',
            'pageSize': '15',
        }
        return params

    # params = {
    #     'orgCode': '325760',
    #     'orderIds': '',
    #     'pageNum': '1',
    #     'shopIds': '',
    #     'pageSize': '15',
    #     'loginName': 'jd_mcyp',
    #     'jdFusion': 'false',
    #     'billType': '1',   # 小时购为2，京东到家为1
    #     'settleStatus': '',
    #     'orderType': '',
    #     'orderStartTime': '20230411',
    #     'orderEndTime': '20230411',
    # }
    params = {
        'orgCode': '325760',
        'orderIds': '',
        'orderId': '',
        'shopIds': '',
        'shopId': '',
        'loginName': 'jd_mcyp',
        'jdFusion': 'false',
        'billType': '1',
        'sourceId': 'pc',
        'srcOrderId': '',
        'userPin': 'jd_mcyp',
        'settleVender': '1',
        'groupNo': '',
        'settleStatus': '',
        'orderType': '',
        'startLastSettleTime': '',
        'endLastSettleTime': '',
        'finishStartTime': '20240610',
        'finishEndTime': '20240610',
        'pageNum': '1',
        'pageSize': '15',
    }

    return params


def jddj_api(start_time=get_yesterday(days=1), end_time=get_yesterday(days=1), type_hour=True, cookie_expire=False, TRY_COUNT=0):
    """
    京东到家---结算管理---对账单查询---商家账单（京东到家）
    京东到家---结算管理---对账单查询---商家账单（小时购）
    :return:
    """
    params = format_jddj_params(type_hour=type_hour)
    params.update({
        'finishStartTime': start_time.replace("-", ""),
        'finishEndTime': end_time.replace("-", ""),
    })
    headers = init_jddj_headers(cookie_expire=cookie_expire)
    url = 'https://dfsc.imdada.cn/settle/search/daoJiaBillList'
    response = requests.get(url=url, params=params, headers=headers)

    if "登录状态失效，请重新登录" in response.text:
        # TRY_COUNT += 1
        # if TRY_COUNT > 2:
        #     return False

        print("登录状态失效")
        print(response.json())
        return False
        # jddj_api(start_time=start_time, end_time=end_time, type_hour=type_hour, cookie_expire=True, TRY_COUNT=TRY_COUNT)


    download_api = "https://dfsc.imdada.cn/settle/supplierCenter/exportBillOrderList?"
    download_url = download_api + urlencode(params)
    res = requests.get(url=download_url, headers=headers)
    # print(res.status_code)
    if not os.path.exists(jddj_download_dir):
        os.mkdir(jddj_download_dir)

    file_name = "jddj_{}_{}_{}.xlsx".format("小时购" if type_hour else "京东到家", params["finishStartTime"], params["finishEndTime"])
    file_path = os.path.join(jddj_download_dir, file_name)
    with open(file_path, "wb") as f:
        f.write(res.content)

    print("{}执行结束".format(file_path))
    return file_path


if __name__ == '__main__':
    jddj_api(type_hour=False)
